from .models import UserInfo
from django.contrib.auth.backends import BaseBackend

class CustomBackend(BaseBackend):
    def authenticate(self, request, **credentials):
        # 从 session 中获取用户 ID
        session_data = request.session.get('_auth_user_id')  # 或其他存储用户 ID 的方式
        if session_data:
            try:
                # 使用自定义的 UserInfo 模型获取用户
                user = UserInfo.objects.get(id=session_data)
                user.backend = 'app1.authentication.CustomBackend'  # 设置 backend 属性
                return user
            except UserInfo.DoesNotExist:
                return None
        return None

    def get_user(self, user_id):
        try:
            # 返回从 session 中获取到的用户
            user = UserInfo.objects.get(id=user_id)
            user.backend = 'app1.authentication.CustomBackend'  # 设置 backend 属性
            return user
        except UserInfo.DoesNotExist:
            return None
